﻿using HardcoreGame.Common.Abstract;
using HardcoreGame.Common.Cores.Seasons;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Collections.Generic;
using Terraria;
using Terraria.GameContent.UI.Elements;
using Terraria.Localization;
using Terraria.ModLoader;
using Terraria.UI;

namespace HardcoreGame.Common.Systems
{
    public class SeasonUISystem : ModSystem
    {
        public UserInterface SeasonInterface;
        public SeasonMainUI SeasonMainUI;

        public static bool UIVisible { get; private set; }
        public static Season SelectedSeason { get; set; }

        public override void Load()
        {
            SeasonMainUI = new SeasonMainUI();
            SeasonInterface = new UserInterface();
            SeasonInterface.SetState(null);
        }

        public override void UpdateUI(GameTime gameTime)
        {
            if (UIVisible)
            {
                SeasonInterface?.Update(gameTime);
            }
        }

        public override void PostDrawInterface(SpriteBatch spriteBatch)
        {
            if (UIVisible)
            {
                SeasonInterface.Draw(spriteBatch, new GameTime());
            }
        }

        public static void ToggleUI()
        {
            UIVisible = !UIVisible;
            if (UIVisible)
            {
                ModContent.GetInstance<SeasonUISystem>().SeasonInterface.SetState(
                    ModContent.GetInstance<SeasonUISystem>().SeasonMainUI);
            }
            else
            {
                ModContent.GetInstance<SeasonUISystem>().SeasonInterface.SetState(null);
            }
        }

        public static void JumpToSeasonDay(int day)
        {
            var seasonSystem = ModContent.GetInstance<SeasonSystem>();

            if (SelectedSeason != null)
            {
                seasonSystem.currentSeason = SelectedSeason;
                seasonSystem.dayCounter = day - 1;

                Main.dayTime = true;
                Main.time = 0;

                seasonSystem.newDayMessage = $"{SelectedSeason.Name} {day}" +
                    Language.GetTextValue("Mods.HardcoreGame.Season.Day");
                seasonSystem.isNewDayMessageDisplayed = true;
                seasonSystem.displayTimer = 0;
            }
        }
    }

    public class SeasonMainUI : UIState
    {
        private UIPanel mainPanel;
        private UIElement daySelectionContainer;
        private const int IconSize = 48;
        private const int ButtonSpacing = 100;
        private bool daySelectionVisible = false;

        public override void OnInitialize()
        {
            mainPanel = new UIPanel();
            mainPanel.Width.Set(600f, 0f);
            mainPanel.Height.Set(320f, 0f);
            mainPanel.HAlign = 0.5f;
            mainPanel.VAlign = 0.5f;
            mainPanel.BackgroundColor = new Color(33, 43, 79) * 0.9f;
            mainPanel.BorderColor = new Color(89, 116, 213);
            Append(mainPanel);

            InitializeSeasonSelection();
            InitializeDaySelection();
            ToggleDaySelection(false);
        }

        private void InitializeSeasonSelection()
        {
            var seasonPanel = new UIPanel();
            seasonPanel.Width.Set(400f, 0f);
            seasonPanel.Height.Set(300f, 0f);
            seasonPanel.Left.Set(10f, 0f);
            seasonPanel.Top.Set(10f, 0f);
            seasonPanel.BackgroundColor = Color.Transparent;
            seasonPanel.BorderColor = Color.Transparent;
            mainPanel.Append(seasonPanel);

            var title = new UIText(Language.GetTextValue("Mods.HardcoreGame.UI.8"))
            {
                HAlign = 0.5f
            };
            title.Top.Set(15f, 0f);
            seasonPanel.Append(title);

            UpdateSeasonInfo(seasonPanel);
            CreateSeasonButtons(seasonPanel);

            var closeButton = new UIText(Language.GetTextValue("Mods.HardcoreGame.UI.7"))
            {
                HAlign = 0.5f
            };
            closeButton.Top.Set(260f, 0f);
            closeButton.OnLeftClick += (evt, element) => SeasonUISystem.ToggleUI();
            seasonPanel.Append(closeButton);
        }

        private void InitializeDaySelection()
        {
            daySelectionContainer = new UIElement();
            daySelectionContainer.Width.Set(180f, 0f);
            daySelectionContainer.Height.Set(300f, 0f);
            daySelectionContainer.Left.Set(410f, 0f);
            daySelectionContainer.Top.Set(10f, 0f);
            mainPanel.Append(daySelectionContainer);

            var dayTitle = new UIText(Language.GetTextValue("Mods.HardcoreGame.UI.9"), 0.8f)
            {
                HAlign = 0.5f
            };
            dayTitle.Top.Set(15f, 0f);
            daySelectionContainer.Append(dayTitle);

            CreateDayButtons();
        }

        private static void UpdateSeasonInfo(UIPanel parentPanel)
        {
            var currentSeason = ModContent.GetInstance<SeasonSystem>().currentSeason;
            var currentDay = ModContent.GetInstance<SeasonSystem>().dayCounter + 1;
            var currentInfo = new UIText(Language.GetTextValue("Mods.HardcoreGame.UI.11") + $"{currentSeason.Name} {currentDay}" + Language.GetTextValue("Mods.HardcoreGame.UI.10"))
            {
                HAlign = 0.5f
            };
            currentInfo.Top.Set(45f, 0f);
            parentPanel.Append(currentInfo);
        }

        private void CreateSeasonButtons(UIPanel parentPanel)
        {
            float buttonTop = 90f;
            float buttonLeft = (400f - (ButtonSpacing * 3)) / 2;

            var seasons = new List<Season>
            {
                new Spring(),
                new Summer(),
                new Autumn(),
                new Winter()
            };

            for (int i = 0; i < seasons.Count; i++)
            {
                var season = seasons[i];
                var buttonContainer = new UIElement
                {
                    Width = new StyleDimension(IconSize, 0f),
                    Height = new StyleDimension(IconSize + 30, 0f),
                    Left = new StyleDimension(buttonLeft + (i * ButtonSpacing), 0f),
                    Top = new StyleDimension(buttonTop, 0f)
                };

                var icon = new UIImage(ModContent.Request<Texture2D>($"HardcoreGame/Content/Biomes/{season.GetType().Name}_Icon"));
                icon.Width.Set(IconSize, 0f);
                icon.Height.Set(IconSize, 0f);
                icon.OnLeftClick += (evt, element) =>
                {
                    SeasonUISystem.SelectedSeason = season;
                    ToggleDaySelection(true);
                };
                buttonContainer.Append(icon);

                var nameText = new UIText(season.Name)
                {
                    HAlign = 0.5f,
                    Top = new StyleDimension(IconSize + 5, 0f),
                    Width = new StyleDimension(IconSize + 20, 0f),
                    Left = new StyleDimension(-10, 0f)
                };
                buttonContainer.Append(nameText);

                buttonContainer.OnLeftClick += (evt, element) =>
                {
                    SeasonUISystem.SelectedSeason = season;
                    ToggleDaySelection(true);
                };

                parentPanel.Append(buttonContainer);
            }
        }

        private void CreateDayButtons()
        {
            const int daysPerRow = 3;
            const int buttonSpacing = 35;

            float startX = (180f - (daysPerRow * buttonSpacing)) / 2;
            float startY = 50f;

            for (int i = 0; i < 12; i++)
            {
                int day = i + 1;
                int row = i / daysPerRow;
                int col = i % daysPerRow;

                var dayButton = new UIText(day.ToString())
                {
                    Left = new StyleDimension(startX + (col * buttonSpacing), 0f),
                    Top = new StyleDimension(startY + (row * 40f), 0f),
                    TextColor = Color.LightGray
                };

                dayButton.OnMouseOver += (evt, element) => dayButton.TextColor = Color.White;
                dayButton.OnMouseOut += (evt, element) => dayButton.TextColor = Color.LightGray;
                dayButton.OnLeftClick += (evt, element) =>
                {
                    SeasonUISystem.JumpToSeasonDay(day);
                    ToggleDaySelection(false);
                };

                daySelectionContainer.Append(dayButton);
            }
        }

        private void ToggleDaySelection(bool show)
        {
            daySelectionVisible = show;
        }
    }
}